package co.fitstart.admin.web.controller;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.DateUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;

import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.handler.SmsSender;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.entity.principal.Principal;

/**
 * 
 * @author Wilson
 * @author Leo
 * 
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(SmsSender.class);
	
    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private SmsSender smsSender;

    /**
     * 
     * @return
     */
    @RequestMapping("/home")
    
    public String home(@Secure Login login) {
        Principal principal = principalService.load(Principal.class, login.getId());
        
        Date latestUpdateTime = principal.getLatestUpdateTime();
        
        if(latestUpdateTime != null && DateUtils.addDays(latestUpdateTime, 28).before(new Date())) {
            return "redirect:/profile/change-password-needed";
        } else {
            if(login.isMarketingManager()) {
                return "redirect:/schedules";
            } else {
                return "redirect:/profile";
            }
        }
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping("/content")
    public String content() {
        return "redirect:/activities";
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping("/system")
    public String system() {
        return "redirect:/profile";
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping("/source")
    public String source() {
        return "redirect:/user-source";
    }
    
    /**
     * 
     * @param login
     * @return
     */
    @RequestMapping("/ecommerce")
    public String ecommerce(@Secure Login login) {
        if(login.isCustomerServer() || login.isAdmin() || login.isRoot()) {
            return "redirect:/individual-orders?status=created";
        }else if(login.isSiteServer() || login.isSiteManager() || login.isAreaManager() || login.isAreaServer()) {
            return "redirect:/individual-orders?status=created";
        } else if (login.isCreditProductManager()) {
            return "redirect:/individual-orders?status=created";
        } else {
            return "redirect:/products";
        }
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping("/credit")
    public String credit() {
        return "redirect:/credit-products";
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping("/user")
    public String user() {
        return "redirect:/users";
    }
    
    /**
     * 
     * @param login
     * @return
     */
    @RequestMapping("/report")
    public String report(@Secure Login login) {
      if(login.isAreaManager() || login.isSiteManager() || login.isAdmin() || login.isRoot() || login.isSiteServer() || login.isAreaServer()) {
          return "redirect:/student-reports";
      } else if(login.isMarketingManager() || login.isMarketing()) {
          return "redirect:/taste-stat-reports";
      } else {
          return "redirect:/profile";
      }
    }
    
    /**
     * 
     * @param login
     * @return
     */
    @RequestMapping("/course")
    public String course(@Secure Login login) {
        if(login.isCustomerServer() || login.isAdmin() || login.isRoot() || login.isCoursewareManager() || login.isCoursewareMonitor() || login.isOnlineCoach()) {
            return "redirect:/individual-rounds";
        } else if(login.isAreaManager() || login.isSiteManager() || login.isSiteServer() || login.isAreaServer()) {
            return "redirect:/individual-rounds";
        } else if(login.isMarketingManager()) {
            return "redirect:/schedules";
        } else {
            return "redirect:/profile";
        }
        
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping("/market")
    public String market() {
        return "redirect:/market-users";
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping("/finance")
    public String finance() {
        return "redirect:/student-archives";
    }
    
    /**
     * 
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/verify-code", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody String sendVerifyCode(@RequestParam("mobile") String mobile) {
    	Result httpResult = new Result();
        
        try {
            if(org.apache.commons.lang3.StringUtils.isNotBlank(mobile)) {
                mobile = mobile.replace(" ", "");
                
                // Generate random code in 6 digits
                String code = smsSender.generateVerifyCode(mobile.trim());
                boolean send = smsSender.sendCode(mobile, code);
                
                if(send) {
                    String token = DigestUtils.sha256Hex(StringUtils.connect(mobile, code, "fitstart"));
                    logger.info("send sms message mobile [{}] token [{}] code [{}]", mobile, token, code);
                    httpResult.success()
                              .data("token", token)
                              .message("发送验证码成功");
                } else {
                    logger.error("#sendVerifyCode() faild with response [{}]", JsonUtils.toJsonString(httpResult));
                    httpResult.fail("501").message("发送验证码失败");
                }
            } else {
                httpResult.fail("1").message("请输入手机号");
            }
        } catch (Exception e) {
            logger.error("#sendVerifyCode() occurs error", e);
            httpResult.fail("500").message("发送验证码请求失败");
        }
        
        return JsonUtils.toJsonString(httpResult);
    }
}
